<template>
  <div class="container">
    <a-row style="margin-bottom: 16px">
      <a-col :span="12">
        <a-space>
          <!-- 新建 -->
          <a-button type="primary" v-if="props.created" @click="createData">
            <template #icon>
              <icon-plus />
            </template>
            {{ $t('searchTable.operation.create') }}
          </a-button>
          <!-- 导入 -->
          <a-button v-if="props.imported" @click="importData">
            <template #icon>
              <icon-upload />
            </template>
            {{ $t('searchTable.operation.import') }}
          </a-button>
        </a-space>
      </a-col>
      <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
        <!-- 下载 -->
        <a-button v-if="props.exported" style="margin-right: 10px;" @click="exportData">
          <template #icon>
            <icon-download />
          </template>
          {{ $t('searchTable.operation.download') }}
        </a-button>
        <!-- 刷新 -->
        <a-tooltip :content="$t('searchTable.actions.refresh')">
          <div class="action-icon" style="margin-right: 10px;" @click="search">
            <icon-refresh size="18" />
          </div>
        </a-tooltip>
        <!-- 密度设置 -->
        <a-dropdown @select="handleSelectDensity">
          <a-tooltip :content="$t('searchTable.actions.density')">
            <div style="margin-right: 10px;" class="action-icon">
              <icon-line-height size="18" />
            </div>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === props.size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
        <!-- 列设置 -->
        <a-tooltip style="margin-right: 10px;" :content="$t('searchTable.actions.columnSetting')">
          <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
            <div class="action-icon">
              <icon-settings size="18" />
            </div>
            <template #content>
              <div id="tableSetting">
                <div v-for="(item) in showColumns" :key="item.dataIndex" class="setting">
                  <div style="margin-right: 4px; cursor: move">
                    <icon-drag-arrow />
                  </div>
                  <div>
                    <a-checkbox v-model="item.checked" @change="handleChange()"></a-checkbox>
                  </div>
                  <div class="title">{{ item.title === '#' ? '序列号' : item.title }}</div>
                </div>
              </div>
            </template>
          </a-popover>
        </a-tooltip>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  ref,
  watch,
  nextTick,
  defineProps,
  defineEmits,
  withDefaults,
} from 'vue';
import { useI18n } from 'vue-i18n';

import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';

import cloneDeep from 'lodash/cloneDeep';
import Sortable from 'sortablejs';

type Column = TableColumnData & { checked?: true };

const { t } = useI18n();

let emit = defineEmits();

// created  true 是否展示新建按钮；imported  true 是否展示导入按钮；download  true 是否展示下载按钮
const props = withDefaults(
  defineProps<{
    size?: string;
    columns?: [];
    created?: boolean;
    imported?: boolean;
    exported?: boolean;
  }>(),
  {
    size: 'medium', // 默认值
    columns: () => [], // 默认值
    created: false, // 默认值
    imported: false, // 默认值
    exported: false, // 默认值
  }
);

const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);

// 密度
const densityList = computed(() => [
  {
    name: t('searchTable.size.mini'),
    value: 'mini',
  },
  {
    name: t('searchTable.size.small'),
    value: 'small',
  },
  {
    name: t('searchTable.size.medium'),
    value: 'medium',
  },
  {
    name: t('searchTable.size.large'),
    value: 'large',
  },
]);

// 新建 触发父组件方法
const createData = () => {
  emit('createData');
};

// 导入
const importData = () => {
  emit('importData');
};

// 导出
const exportData = () => {
  emit('exportData');
};

// 刷新
const search = () => {
  emit('search');
};

// 密度设置
const handleSelectDensity = (
  val: string | number | Record<string, any> | undefined,
  e: Event
) => {
  emit('handleSelectDensity', val);
};

// 列设置 - 选择某列
const handleChange = (
  checked: boolean | (string | boolean | number)[],
  column: Column,
  index: number
) => {
  cloneColumns.value = showColumns.value.filter(
    (item) => item.checked === true
  );
  emit('handleCloneColumns', cloneColumns.value);
};

// 列设置 - 替换列数组
const exchangeArray = <T extends Array<any>>(
  array: T,
  beforeIdx: number,
  newIdx: number,
  isDeep = false
): T => {
  const newArray = isDeep ? cloneDeep(array) : array;
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(
      beforeIdx,
      1,
      newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
    );
  }
  return newArray;
};

// 列设置渲染
const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement;
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const { oldIndex, newIndex } = e;
          exchangeArray(cloneColumns.value, oldIndex, newIndex);
          exchangeArray(showColumns.value, oldIndex, newIndex);
        },
      });
    });
  }
};

// 监听列
watch(
  () => props.columns,
  (val) => {
    cloneColumns.value = cloneDeep(val);
    cloneColumns.value.forEach((item, index) => {
      item.checked = true;
    });
    showColumns.value = cloneDeep(cloneColumns.value);
    emit('handleCloneColumns', cloneColumns.value);
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="less">
.container {
  padding: 0px 0px 0px 0px;
}
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
.action-icon {
  margin-left: 12px;
  cursor: pointer;
}
.active {
  color: #0960bd;
  background-color: #e3f4fc;
}
.setting {
  display: flex;
  align-items: center;
  width: 200px;
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
